<template>
  <basic-container>
    <!--        {{ optionData.columnList }}-->
    <!--    {{optionData.data}}-->
    <!--    {{optionData.selectionList}}-->
    <szTable :fieldList="optionData.columnList" @onLoad="onLoad" :permission="optionData.permission"
             :fieldData="optionData.dataList" :sceneList="optionData.sceneList"
             :cellClassName="cellClassName"
             @rowSave="rowSave"
             @rowUpdate="rowUpdate"
             @rowView="rowView"
             @searchChange="onLoad"
             @row-click="onRowClick"
             @sort-change="onSortChange"
             @header-dragend="onHeaderDragend"
             @select="onSelect"
             @selection-change="onSelectionChange">
      <template v-slot:menu-left>
        <!--根据权限判断是否显示操作按钮-->
        <!--v-show="whetherTypeShowByPermision(item.type)"-->
        <el-button v-for="(item, index) in getSelectionHandleItemsInfo()"
                   :key="index"
                   type="primary"
                   @click="selectionBarClick(item.type)">{{ item.name }}
        </el-button>

        <template v-if="menuDialogShow.transferDialogShow">
          <MyTransferHandle crm-type="customer"
                            :selection-list="optionData.selectionList"
                            v-model:dialogVisible="menuDialogShow.transferDialogShow"
                            @handle="handleCallBack"/>
        </template>
        <template v-if="menuDialogShow.teamsDialogShow">
          <MyTeamsHandle crm-type="customer" :type="optionData.teamsType"
                         :selection-list="optionData.selectionList"
                         v-model:dialog-visible="menuDialogShow.teamsDialogShow"
                         @handle="handleCallBack"/>
        </template>

        <MyAllocHandle crm-type="customer"
                       :pool-id="optionData.poolId"
                       :selection-list="optionData.selectionList"
                       :dialog-visible="menuDialogShow.allocDialogShow"
                       @handle="handleCallBack"/>
        <MyDealStatusHandle crm-type="customer"
                            :selection-list="optionData.selectionList"
                            v-model:visible="menuDialogShow.dealStatusShow"
                            @handle="handleCallBack"/>
        <MyPutPoolHandle v-model:visible="menuDialogShow.putPoolShow"
                         :selection-list="optionData.selectionList"
                         @handle="handleCallBack"/>
      </template>
      <template v-slot:menu-right>
        <el-button type="danger">右侧按钮</el-button>
      </template>

      <!--自定义的列-->
      <template v-slot:cellSlot="{cellData} ">
        <!--成交状态-->
        <template v-if="cellData.column.property == 'dealStatus'">
          <i :class="dealIcon(cellData.row[cellData.column.property ])"/>
          <span>{{ dealName(cellData.row[cellData.column.property]) }}</span>
        </template>
        <!--锁定状态-->
        <template v-else-if="cellData.column.property == 'status'">
          <i v-if="cellData.row.status == 2" class="wk wk-circle-password customer-lock"/>
        </template>
        <template v-if="cellData.column.property == 'checkStatus'">
          <span :style="{backgroundColor: hookCheckStatusMixin.getStatusColor(data.row.checkStatus)}"
                class="status-mark"/>
          <span>{{ hookCheckStatusMixin.getStatusName(data.row.checkStatus) }}</span>
        </template>
        <template v-else-if="cellData.column.property == 'receivedStatus'">
          {{ hookCheckStatusMixin.getPlanReceivablesStatusName(cellData.row.receivedStatus) }}
        </template>
        <template v-else-if="cellData.column.property == 'businessCheck'">
          <!-- 以弹出框的形式显示商机信息，包括商机个数、商机名称、商机金额、客户名称、商机状态组、状态-->
          <el-popover ref="businessCheckRef" :disabled="cellData.row.businessCount == 0"
                      placement="right" :offset="20"
                      width="500" trigger="click">
            <template v-slot:default>
              <BusinessCheck :data="cellData" :show="cellData.row.show"/>
              <!--@click="relativeBusinessClick"-->
              <!--@close="businessClose($event, scope)"-->
            </template>
            <template v-slot:reference>
              <i :style="{'opacity' : cellData.row.businessCount > 0 ? 1 : 0}"
                 class="wk wk-business" style="color: #FC6E51"/>
              <!--@click="businessCheckClick($event, scope)"-->
            </template>
          </el-popover>
        </template>
      </template>

      <!--自定义操作列-->
      <template v-slot:operationColumn="{data} ">
        <template v-if="optionData.starShow">
          <!--关注-->
          <el-tooltip :content="data.row.star == 0 ? '添加关注' : '取消关注'" effect="dark" placement="top">
            <i :class="{active: data.row.star != 0}"
               class="wk wk-focus-on focus-icon" @click="toggleStar(data.row, optionData.crmType)"/>
          </el-tooltip>
          <!--操作按钮-->
          <el-button type="primary" size="small">Test</el-button>
        </template>
      </template>
    </szTable>

    <!--创建-->
    <CustomerCreate v-if="optionData.dialogShow.create"
                    :action="optionData.createAction"
                    @close="optionData.dialogShow.create = false"
                    @save-success="handleHandle">
    </CustomerCreate>

    optionData.rowId：{{ optionData.rowId }}
    optionData.rowIndex:{{ optionData.rowIndex }}
    <!--详情-->
    <CustomerDetail v-model:visible="optionData.dialogShow.detail"
                    v-model:id="optionData.rowId"
                    :detail="optionData.detailData"
                    :pageList="optionData.dataList"
                    v-model:pageIndex="optionData.rowIndex"
                    class="d-view"
                    @hide-view="optionData.dialogShow.detail=false"
                    @handle="handleHandle"></CustomerDetail>
  </basic-container>

</template>


<script setup>
import szTable from '../component/table/index.vue'
import {
  crmFieldColumnWidthAPI,
  crmPoolFieldColumnWidthAPI,
  crmSceneIndexAPI,
  filedGetPoolTableFieldAPI,
  filedGetTableFieldAPI
} from "@/api/crm/common.js";
import {downloadExcelWithResData} from "utils";
import { reactive, } from "vue";
import {
  crmCustomerDeleteAPI,
  crmCustomerExcelExportAPI,
  crmCustomerLockAPI, crmCustomerReceiveAPI
} from "@/api/crm/customer.js";
import {useCheckStatusHook as hookCheckStatusMixin} from "@/mixins/useCheckStatusHook.js";
import BusinessCheck from "@/views/crm/customer/comp/BusinessCheck.vue";
import MyDealStatusHandle from "@/views/scrm/component/action/MyDealStatusHandle.vue";
import MyTransferHandle from "@/views/scrm/component/action/MyTransferHandle.vue";
import MyTeamsHandle from "@/views/scrm/component/action/MyTeamsHandle.vue";
import MyAllocHandle from "@/views/scrm/component/action/MyAllocHandle.vue";
import MyPutPoolHandle from "@/views/scrm/component/action/MyPutPoolHandle.vue";
import {crmLeadsDeleteAPI, crmLeadsExcelExportAPI, crmLeadsStarAPI, crmLeadsTransformAPI} from "@/api/crm/leads.js";
import {crmContactsDeleteAPI, crmContactsExcelExportAPI, crmContactsStarAPI} from "@/api/crm/contacts.js";
import {crmBusinessDeleteAPI, crmBusinessExcelExportAPI, crmBusinessStarAPI} from "@/api/crm/business.js";
import {crmContractDeleteAPI, crmContractExcelExportAPI} from "@/api/crm/contract.js";
import {crmReceivablesDeleteAPI, crmReceivablesExcelExportAPI} from "@/api/crm/receivables.js";
import {crmReceivablesPlanDeleteAPI, crmReceivablesPlanExcelExportAPI} from "@/api/crm/receivablesPlan.js";
import {crmProductDeleteAPI, crmProductExcelExportAPI, crmProductStatusAPI} from "@/api/crm/product.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {crmReturnVisitDeleteAPI} from "@/api/crm/visit.js";
import CustomerCreate from "./create.vue"
import CustomerDetail from "./detail.vue"
import {useSelectionItemHook} from "@/views/scrm/customer/index/useSelectionItemHook.js";
import {useCrmStore} from "@/store/modules/crm.js";
import {toggleStar} from "@/views/scrm/customer/index/starHandle.js";
import {useFieldAndListAndDataHook} from "@/views/scrm/customer/index/useFieldAndListAndDataHook.js";

const optionData = reactive({
  crmType: 'customer',
  /**
   * 解释
   * prop: fieldName : customerName
   * forType: formType: text
   * label: name: "客户名称"
   * width: width : 100
   * sortId: id: 35263
   */
  // 列属性
  columnList: [],
  // 表格数据
  dataList: [],
  //搜索对象
  search: {},

  // 场景参数
  sceneList: [],
  sceneSelectId: null,
  // 场景参数

  // 分页参数 start
  page: {
    pageSize: 10,
    currentPage: 1,
    total: 0
  },
  // 分页参数 End

  // 权限
  permission: {
    addBtn: true,
    viewBtn: true,
    delBtn: true,
    editBtn: true,
    importBtn: false,
    exportBtn: false
  },
  // 权限
  // 对话框显示控制标志
  dialogShow: {
    create: false,
    update: false,
    detail: false,
  },

  // 团队操作类型
  teamsType: '',

  // 表格选择相关
  rowIndex: 0, // 行索引
  rowId: '', // 行信息
  selectionList: [], //表格中选择的行
  detailData: {}, //编辑的时候，需要传递详情
  // 表格选择相关

  formatter: {
    "dealStatus": ""
  },
  createAction: {
    type: 'save',
    id: '',
    data: {}
  },
  form: {},


  starShow: true,


  option: {},

})
const {page, form} = toRefs(optionData)

// createVNode 使用方法：https://www.861ppt.com/news/33860.html

/**
 * 通过回调控制class
 */
function cellClassName({row, column, rowIndex, columnIndex}) {
  if (column.property === 'customerName') {
    return 'can-visit--underline'
  } else if (column.property === 'businessCheck') {
    return 'can-visit'
  } else {
    return ''
  }
}

function dealIcon(status) {
  return status == 1 ? 'wk wk-success deal-suc' : 'wk wk-close deal-un'
}

function dealName(status) {
  return status == 1 ? '已成交' : '未成交'
}


onMounted(() => {
  onLoad()
})


function onLoad() {
  console.log("onLoad")
  getFieldList();
  getList()
  getSceneList()
}

const fieldAndListAndDataHook = useFieldAndListAndDataHook();

/**
 * 获取字段的信息
 */
function getFieldList() {
  fieldAndListAndDataHook.getFieldList('customer').then((res) => {
    optionData.columnList = res
  })
}

/**
 * 获取列表数据
 */
function getList() {
  fieldAndListAndDataHook.getList('customer', optionData.page, optionData.search).then((res) => {
    optionData.dataList = res
  })
}

/**
 * 详情
 */
function getDetail(id) {
  fieldAndListAndDataHook.getDetail(id).then(res => {
    optionData.detailData = res
  })
}

/**
 * 获取场景列表
 */
const getSceneList = () => {
  fieldAndListAndDataHook.getSceneList(optionData.crmType).then(result => {
    const resData = result || []
    // 默认场景列表
    const defaultSceneList = resData.filter(item => item.isDefault === 1)
    // 当前的场景
    let currentScene = null

    if (defaultSceneList && defaultSceneList.length > 0) {
      // 如果存在默认场景列表，将当前场景设置为默认场景的第一个
      currentScene = defaultSceneList[0]
    } else if (resData.length > 0) {
      // 如果没有默认场景，将当前场景设置成返回值的第一个
      currentScene = resData[0]
    }

    // 找到了当前显示的场景
    if (currentScene) {
      currentScene.id = currentScene.sceneId
      currentScene.bydata = currentScene.bydata || ''
      optionData.sceneSelectId = currentScene.sceneId
    }
    optionData.sceneList = resData
  })
}

const selectionItemHook = useSelectionItemHook();

/** 获取展示items */
function getSelectionHandleItemsInfo() {
  return selectionItemHook.customerSelectionItemHandle();
}


const menuDialogShow = reactive({
  transferDialogShow: false,
  teamsDialogShow: false, // 团队操作提示框
  allocDialogShow: false, // 公海分配操作提示框
  dealStatusShow: false, // 成交状态修改框
  putPoolShow: false, // 客户放入公海
})

// 如果被内部改变了rowId，需要重新获取数据，并传入
watch(() => optionData.rowId, (value) => {
  if(value != null) {
    getDetail(optionData.rowId);
  }
})

/** 操作 */
function selectionBarClick(type) {
  console.log("type", type)

  if (type == 'transfer') {
    // 转移
    menuDialogShow.transferDialogShow = true
  } else if (type == 'export') {
    let params = {}
    let request = null

    request = {
      customer: crmCustomerExcelExportAPI,
      leads: crmLeadsExcelExportAPI,
      contacts: crmContactsExcelExportAPI,
      business: crmBusinessExcelExportAPI,
      contract: crmContractExcelExportAPI,
      receivables: crmReceivablesExcelExportAPI,
      receivablesPlan: crmReceivablesPlanExcelExportAPI,
      product: crmProductExcelExportAPI
    }[crmOption.crmType]
    params = optionData.selectionList.map(item => item[`${crmOption.crmType}Id`])

    request(params).then(res => {
      downloadExcelWithResData(res)
    }).catch(() => {
    })
  } else if (type == 'transform' ||
      type == 'delete' ||
      type == 'lock' ||
      type == 'unlock' ||
      type == 'start' ||
      type == 'disable' ||
      type == 'get') {
    let message = ''
    if (type == 'transform') {
      message = '确定将这些线索转换为客户吗?'
    } else if (type == 'delete') {
      message = `确定删除选中的${optionData.selectionList.length}项吗？`
    } else if (type == 'lock') {
      message = '确定要锁定这些客户吗？锁定后将不会掉入公海。'
    } else if (type == 'unlock') {
      message = '确定要解锁这些客户吗？'
    } else if (type == 'start') {
      message = '确定要上架这些产品吗?'
    } else if (type == 'disable') {
      message = '确定要下架这些产品吗?'
    } else if (type == 'get') {
      message = '确定要领取该客户吗?'
    }

    ElMessageBox.confirm(message, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      confirmHandle(type)
    }).catch(() => {
    })
  } else if (type == 'add_user') {
    // 团队操作
    optionData.teamsType = 'add'
    menuDialogShow.teamsDialogShow = true
  } else if (type == 'delete_user') {
    // 团队操作
    optionData.teamsType = 'delete'
    menuDialogShow.teamsDialogShow = true
  } else if (type == 'alloc') {
    // 公海分配操作
    menuDialogShow.allocDialogShow = true
  } else if (type == 'deal_status') {
    // 客户成交状态操作
    menuDialogShow.dealStatusShow = true
  } else if (type == 'put_seas') {
    // 客户放入公海
    menuDialogShow.putPoolShow = true
  }
}


function confirmHandle(type) {
  if (type === 'lock' || type === 'unlock') {
    crmCustomerLockAPI({
      // 1是正常 2是锁定
      status: type === 'lock' ? '2' : '1',
      ids: optionData.selectionList.map(item => item.customerId).join(',')
    }).then(res => {
      ElMessage.success({message: '操作成功'})
      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'transform') {
    crmLeadsTransformAPI(optionData.selectionList.map(item => item.leadsId)).then(res => {
      ElMessage.success({message: '转化成功'})
      // 刷新待办
      const crmStore = useCrmStore();
      crmStore.GetMessageNum()
      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'start' || type === 'disable') {
    crmProductStatusAPI({
      ids: optionData.selectionList.map(item => item.productId),
      status: type === 'start' ? '1' : '0'
    }).then(res => {
      ElMessage.success({message: '操作成功'})
      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'delete') {
    const ids = optionData.selectionList.map(item => item[optionData.crmType + 'Id'])
    const request = {
      leads: crmLeadsDeleteAPI,
      customer: crmCustomerDeleteAPI,
      contacts: crmContactsDeleteAPI,
      business: crmBusinessDeleteAPI,
      contract: crmContractDeleteAPI,
      receivables: crmReceivablesDeleteAPI,
      receivablesPlan: crmReceivablesPlanDeleteAPI,
      visit: crmReturnVisitDeleteAPI,
      product: crmProductDeleteAPI
    }[optionData.crmType]
    console.log("crmOption.crmType3", optionData.crmType)
    const params = {}
    params.ids = ids
    request(ids).then(res => {
      if (res.data.code != 0) {
        ElMessage.error({message: res.data.msg})
      } else {
        ElMessage.success({message: '删除成功'})
      }
      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'get') {
    // 领取
    crmCustomerReceiveAPI({
      ids: optionData.selectionList.map(item => item.customerId),
      poolId: crmOption.poolId
    }).then(res => {
      ElMessage.success({message: '操作成功'})
      // 刷新待办
      const crmStore = useCrmStore();
      crmStore.GetMessageNum()
      emits('handle', {type: type})
    }).catch(() => {
    })
  }
}


// 子组件 回调的 结果
function handleCallBack(data) {
  // emits('handle', {type: data.type})
  onLoad()
}


//表格的事件回调处理
// 新增按钮的回调
function rowSave() {
  optionData.createAction = {
    type: 'save',
    id: '',
    data: {}
  }
  optionData.dialogShow.create = true
}

// 编辑按钮的回调
async function rowUpdate() {
  // 更新和详情需要先通过接口拿到详情数据后再处理
  await getDetail(optionData.selectionList[0]["customerId"])
  optionData.createAction = {
    type: 'update',
    id: optionData.selectionList[0]["customerId"],
    data: optionData.selectionList[0],
    batchId: optionData.detailData.batchId
  }
  optionData.dialogShow.create = true
}

// 查看按钮的回调
async function rowView() {
  await getDetail(optionData.selectionList[0]["customerId"])
  console.log("rowView", optionData.selectionList)
  optionData.dialogShow.detail = !optionData.dialogShow.detail
}

// 点击行的回调函数
function onRowClick(row, column, event) {
  // (row: any, column: any, event: Event) => void

}

// 排序的回调
function onSortChange(column, prop, order) {
  // (data: {column: any, prop: string, order: any }) => void
  // 设置当前页面为第一页，设置查询的对象，执行查询动作
}

// 当拖动表头改变了列的宽度的时候会触发该事件
function onHeaderDragend(newWidth, oldWidth, column, event) {
  // (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => void
  // 存在属性名称才可以
  if (column.property) {
    let sortId
    optionData.columnList.forEach(e => {
      if (column.property === e.prop) {
        sortId = e.sortId
      }
    })
    if (!sortId) {
      return
    }
    const params = {
      id: sortId,
      width: newWidth,
      field: column.property
    }

    crmFieldColumnWidthAPI(params).then(res => {
    }).catch(() => {
    })
  }

}

// 选择一行后的回调
function onSelect(selection) {
  // (newSelection: any[]) => void
  console.log("newSelection onSelect", selection)
}

// 宣传变化的回调
function onSelectionChange(newSelection) {
  // (newSelection: any[]) => void
  console.log("newSelection", newSelection)
  optionData.selectionList = newSelection;
  /**
   * 防止取消选择的时候，出现报错。因为此时已经取不到第0个值了
   */
  if (newSelection != null && newSelection.length > 0) {
    optionData.rowId = newSelection[newSelection.length - 1]['customerId'];
  } else {
    optionData.rowId = null;
  }
}

//表格的事件回调处理


function handleHandle(data) {

}

</script>


<style scoped lang="scss">
@import '../../crm/styles/table';
</style>